<?php

namespace app\admin\controller;

use app\model\PickUpPointModel;
use support\Request;
use support\Response;
use Exception;
use app\model\OrderModel;
use app\model\OrderItemModel;

class PickUpPointController
{
    /**
     * 获取配送点列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            $name = $request->get('name', '');
            $city_id = $request->get('city_id', '');
            $status = $request->get('status', '');
            
            $query = PickUpPointModel::query()
                ->orderBy('id', 'desc');
                
            // 按名称搜索
            if (!empty($name)) {
                $query->where('name', 'like', '%' . $name . '%');
            }
            
            // 按城市ID搜索
            if (!empty($city_id)) {
                $query->where('city_id', $city_id);
            }
            
            // 按状态搜索
            if ($status !== '') {
                $query->where('status', $status);
            }
                
            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['updated_at'] = date('Y-m-d H:i:s', $item->updated_at);
                $item['status_text'] = $item->status ? '启用' : '禁用';
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取配送点详情
     * @param Request $request
     * @return Response
     */
    public function detail(Request $request): Response
    {
        try {
            $id = $request->get('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $pickUpPoint = PickUpPointModel::find($id);
            if (!$pickUpPoint) {
                throw new Exception('配送点不存在');
            }

            $pickUpPoint['created_at'] = date('Y-m-d H:i:s', $pickUpPoint->created_at);
            $pickUpPoint['updated_at'] = date('Y-m-d H:i:s', $pickUpPoint->updated_at);

            return json([
                'data' => $pickUpPoint,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 创建配送点
     * @param Request $request
     * @return Response
     */
    public function create(Request $request): Response
    {
        try {
            $data = $request->post();
            
            // 参数验证
            if (empty($data['name'])) {
                throw new Exception('配送点名称不能为空');
            }
            if (empty($data['province'])) {
                throw new Exception('省份不能为空');
            }
            if (empty($data['city'])) {
                throw new Exception('城市不能为空');
            }
            if (empty($data['address'])) {
                throw new Exception('详细地址不能为空');
            }
            if (empty($data['phone'])) {
                throw new Exception('联系电话不能为空');
            }
            if (empty($data['city_id'])) {
                throw new Exception('城市ID不能为空');
            }

            // 设置默认值
            $data['status'] = $data['status'] ?? 1;
            $data['created_at'] = time();
            $data['updated_at'] = time();

            $id = PickUpPointModel::insertGetId($data);
            if (!$id) {
                throw new Exception('创建失败');
            }

            return json([
                'data' => ['id' => $id],
                'msg' => '创建成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 更新配送点
     * @param Request $request
     * @return Response
     */
    public function update(Request $request): Response
    {
        try {
            $data = $request->post();
            $id = $data['id'] ?? null;
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            // 检查配送点是否存在
            $pickUpPoint = PickUpPointModel::find($id);
            if (!$pickUpPoint) {
                throw new Exception('配送点不存在');
            }

            // 参数验证
            if (empty($data['name'])) {
                throw new Exception('配送点名称不能为空');
            }
            if (empty($data['province'])) {
                throw new Exception('省份不能为空');
            }
            if (empty($data['city'])) {
                throw new Exception('城市不能为空');
            }
            if (empty($data['address'])) {
                throw new Exception('详细地址不能为空');
            }
            if (empty($data['phone'])) {
                throw new Exception('联系电话不能为空');
            }
            if (empty($data['city_id'])) {
                throw new Exception('城市ID不能为空');
            }

            $data['updated_at'] = time();
            unset($data['id']); // 移除ID字段

            $result = PickUpPointModel::where('id', $id)->update($data);
            if (!$result) {
                throw new Exception('更新失败');
            }

            return json([
                'data' => null,
                'msg' => '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除配送点
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            // 检查配送点是否存在
            $pickUpPoint = PickUpPointModel::find($id);
            if (!$pickUpPoint) {
                throw new Exception('配送点不存在');
            }

            $result = PickUpPointModel::where('id', $id)->delete();
            if (!$result) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 更新配送点状态
     * @param Request $request
     * @return Response
     */
    public function updateStatus(Request $request): Response
    {
        try {
            $id = $request->post('id');
            $status = $request->post('status');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }
            if (!in_array($status, [0, 1])) {
                throw new Exception('状态值无效');
            }

            // 检查配送点是否存在
            $pickUpPoint = PickUpPointModel::find($id);
            if (!$pickUpPoint) {
                throw new Exception('配送点不存在');
            }

            $result = PickUpPointModel::where('id', $id)->update([
                'status' => $status,
                'updated_at' => time()
            ]);
            if (!$result) {
                throw new Exception('状态更新失败');
            }

            return json([
                'data' => null,
                'msg' => '状态更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function dayGoodsList(Request $request): Response
    {
        try {
            $startDate = $request->get('startDate');
            $endDate = $request->get('endDate');

            $query = OrderModel::query()
            ->where('express_type', OrderModel::EXPRESS_TYPE_PICK_UP_POINT)
            ->where('pay_status', '=', 1);

            if(!empty($startDate)){
                $startDate = strtotime($startDate);
                $query->where('pay_time', '>=', $startDate);
            }

            if(!empty($endDate)){
                $endDate = strtotime($endDate) +86400 ;
                $query->where('pay_time', '<', $endDate);
            }

            $goodsData = [];
            foreach($query->get() as $o){
                $items = OrderItemModel::where('order_id', $o->id)->get();
                foreach($items as $item){
                    $specData = [];
                    if(isset($goodsData[$item->goods_id])){
                        $specData = $goodsData[$item->goods_id]['specs'];
                    }else{
                        $goodsData[$item->goods_id] = [
                            'name' => $item->goods_title,
                            'specs'=>[]
                        ];
                    }

                    if(isset($specData[$item->goods_ku_id])){
                        $specData[$item->goods_ku_id]['quantity'] += $item->quantity;
                    }else{
                        $skuSpecNames = $item->sku_spec_names;
                        $skuSpecNames = json_decode($skuSpecNames, true);
                        $skuSpecNames = implode(' / ', $skuSpecNames);
                        $specData[$item->goods_ku_id] = [
                            'name' => $skuSpecNames,
                            'quantity' => $item->quantity,
                        ];
                    }

                    $goodsData[$item->goods_id]['specs'] = $specData;
                }
            }

            return json([
                'data' => [
                    'list' => $goodsData,
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        }catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取配送点订单数据汇总
     * @param Request $request
     * @return Response
     */
    public function pickupOrdersSummary(Request $request): Response
    {
        try {
            $date = $request->get('date'); // 查询日期 YYYY-MM-DD
            
            if (empty($date)) {
                throw new Exception('请选择查询日期');
            }

            $startTime = strtotime($date);
            $endTime = $startTime + 86400; // 加一天

            // 查询指定日期的配送点订单
            $orders = OrderModel::query()
                ->with(['pick_up_point', 'items', 'user'])
                ->where('express_type', OrderModel::EXPRESS_TYPE_PICK_UP_POINT)
                ->where('pay_status', 1) // 已支付
                ->where('pay_time', '>=', $startTime)
                ->where('pay_time', '<', $endTime)
                ->orderBy('pick_up_point_id')
                ->orderBy('pay_time')
                ->get();

            // 按配送点分组
            $pickupOrders = [];
            foreach ($orders as $order) {
                $pickupPointId = $order->pick_up_point_id;
                
                if (!isset($pickupOrders[$pickupPointId])) {
                    $pickupOrders[$pickupPointId] = [
                        'pickup_point' => $order->pick_up_point ? [
                            'id' => $order->pick_up_point->id,
                            'name' => $order->pick_up_point->name,
                            'address' => $order->pick_up_point->address,
                            'phone' => $order->pick_up_point->phone,
                            'province' => $order->pick_up_point->province,
                            'city' => $order->pick_up_point->city,
                        ] : null,
                        'orders' => []
                    ];
                }

                // 处理订单商品信息
                $orderItems = [];
                foreach ($order->items as $item) {
                    $skuSpecNames = json_decode($item->sku_spec_names, true);
                    $skuSpecNames = is_array($skuSpecNames) ? implode(' / ', $skuSpecNames) : $item->sku_spec_names;
                    
                    $orderItems[] = [
                        'goods_id' => $item->goods_id,
                        'goods_title' => $item->goods_title,
                        'sku_spec_names' => $skuSpecNames,
                        'quantity' => $item->quantity,
                        'price' => round($item->unit_price,precision: 2),
                        'total_price' => round($item->total_price,2),
                    ];
                }

                $pickupOrders[$pickupPointId]['orders'][] = [
                    'order_id' => $order->id,
                    'order_no' => $order->order_no,
                    'user_name' => $order->receiver_name,
                    'user_phone' => substr_replace($order->receiver_phone, '****', 3, 4),
                    'pay_time' => date('Y-m-d H:i:s', $order->pay_time),
                    'pay_amount' => round($order->pay_amount,2),
                    'total_amount' => round($order->total_amount,2),
                    'discount_amount' => round($order->discount_amount,2),  
                    'items' => $orderItems,
                ];
            }

            // 转换为数组格式
            $result = array_values($pickupOrders);

            return json([
                'data' => [
                    'list' => $result,
                    'total_pickup_points' => count($result),
                    'total_orders' => $orders->count(),
                    'query_date' => $date,
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
}
